# -*- coding: utf-8 -*-

from com.maycur.grpc.base.base_entity import java_utils_dict
from com.maycur.grpc.base.java_loader import JavaImportInfo, JavaFieldInfo
from com.maycur.grpc.base.java_loader import JavaClassInfo
from com.maycur.utils import CommonUtils


def append_import_to_line(class_info: JavaClassInfo, import_path: str, append_line_idx: int):
    if import_path not in class_info.import_dict:
        import_line = f'import {import_path};\n'
        class_info.lines[append_line_idx] += import_line
        import_info = JavaImportInfo()
        import_info.path = import_path
        import_info.line_idx = append_line_idx
        class_info.import_dict[import_info.path] = import_info


def enrich_nested_converter(base_converter: JavaClassInfo, nested_converter: JavaClassInfo):
    """
    import nested converter and add @Autowired if not exist
    :param base_converter: the wrapper converter
    :param nested_converter: the dependant converter
    :return: None
    """
    indents = ' ' * 4
    if base_converter.simple_name == nested_converter.simple_name:
        # no need to import and enrich
        return
    for item in base_converter.fields:
        # already enriched
        if item.type == nested_converter.simple_name:
            return

    # determine where to put @Autowired
    class_found = False
    class_line_idx = -1
    import_idx = 1
    lines_len = len(base_converter.lines)
    for idx in range(0, lines_len):
        if ' class ' in base_converter.lines[idx]:
            class_found = True
        if '{' in base_converter.lines[idx] and class_found:
            class_line_idx = idx
            break

    field_info = JavaFieldInfo()
    field_info.name = CommonUtils.lower_first(nested_converter.simple_name)
    field_info.type = nested_converter.simple_name
    auto_wired_line = f'{indents}@Autowired\n{indents}private {field_info.type} {field_info.name};\n'
    base_converter.lines[class_line_idx] = base_converter.lines[class_line_idx] + '\n' + auto_wired_line

    base_converter.fields.append(field_info)
    append_import_to_line(base_converter, java_utils_dict['Autowired'], import_idx)
